package com.xue.impl.sqlBase;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;

import com.google.common.collect.Lists;
import com.xue.impl.sqlBase.execute.Row;
import com.xue.impl.sqlBase.parser.SqlParser;
import com.xue.impl.sqlBase.tree.Identifier;
import com.xue.impl.sqlBase.tree.Query;
import com.xue.impl.sqlBase.tree.QuerySpecification;
import com.xue.impl.sqlBase.tree.SelectItem;
import com.xue.impl.sqlBase.tree.SingleColumn;
import com.xue.impl.sqlBase.tree.Statement;
import com.xue.impl.sqlBase.tree.Table;

/**
 * Hello world!
 *
 */
public class SqlBaseTestMain {
	private static String dataDir = "D:/xuejianxin/work20180326New/springboot2/sqltest/doc/selectBase/data";

	public static void main(String[] args) throws IOException {

		System.out.print(">> ");
		String inputFile = null;
		if (args.length > 0)
			inputFile = args[0];
		InputStream is = System.in;
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		String sql = reader.readLine();
//        String sql = "select City, City from cities";

		SqlParser sqlParser = new SqlParser();

		Statement statement = sqlParser.createStatement(sql);

		if (statement instanceof Query) {
			handleQuery((Query) statement);

		} else {
			System.out.println("unsupported!!");
		}

	}

	public static void handleQuery(Query query) throws IOException {
		/**
		 * 获取待查询的表名和字段名称
		 */
		QuerySpecification specification = (QuerySpecification) query.getQueryBody();
		Table table = (Table) specification.getFrom().get();
		List<SelectItem> selectItems = specification.getSelect().getSelectItems();
		List<String> fieldNames = Lists.newArrayList();
		for (SelectItem item : selectItems) {
			SingleColumn column = (SingleColumn) item;
			fieldNames.add(((Identifier) column.getExpression()).getValue());
		}

		/**
		 * 基于表名确定查询的数据源文件
		 */
		String fileLoc = String.format("%s/%s.csv",dataDir, table.getName());

		/**
		 * 从csv文件中读取指定的字段
		 */
		Reader in = new FileReader(fileLoc);
		Iterable<CSVRecord> records = CSVFormat.RFC4180.withFirstRecordAsHeader().parse(in);
		List<Row> rowList = Lists.newArrayList();
		for (CSVRecord record : records) {
			Row row = new Row();
			for (String field : fieldNames) {
				row.addColumn(record.get(field));
			}
			rowList.add(row);
		}

		/**
		 * 格式化输出到控制台
		 */
		int width = 30;
		String format = fieldNames.stream().map(s -> "%-" + width + "s").collect(Collectors.joining("|"));
		System.out.println("|" + String.format(format, fieldNames.toArray()) + "|");

		int flagCnt = width * fieldNames.size() + fieldNames.size();
		String rowDelimiter = String.join("", Collections.nCopies(flagCnt, "-"));
		System.out.println(rowDelimiter);
		for (Row row : rowList) {
			System.out.println("|" + String.format(format, row.getColumnList().toArray()) + "|");
		}
	}
}
